#include "RectangleRegionDrawer.h"
#include <QPen>
#include <QBrush>
#include <QGraphicsScene>
#include <QGraphicsRectItem>
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsSceneHoverEvent>
#include <QPainter>
#include <QDebug>
#include <QtMath>

// 包含MeasurementMode的定义
#include "MeasurementAlgorithmBase.h"

// 包含公共DraggableRectItem类的定义
#include "../Common/DraggableRectItem.h"

// RectangleRegionDrawer类实现
RectangleRegionDrawer::RectangleRegionDrawer(QObject *parent) 
    : QObject(parent),
      m_scene(nullptr),
      m_rectItem(nullptr),
      m_imageWidth(0),
      m_imageHeight(0),
      m_scale(1.0),
      m_offset(QPointF()),
      m_fillOpacity(0.3)
{
    initializeStyles();
}

RectangleRegionDrawer::~RectangleRegionDrawer()
{
    clearAll();
}

void RectangleRegionDrawer::setScene(QGraphicsScene *scene)
{
    if (m_scene != scene) {
        // 清除之前场景中的绘制项
        clearAll();
        m_scene = scene;
    }
}



void RectangleRegionDrawer::initializeRectangle(int imageWidth, int imageHeight, double scale, const QPointF &offset, 
                                               int defaultWidth, int defaultHeight)
{
    if (!m_scene) {
        qWarning() << "m_scene error";
        return;
    }

    // 保存图像参数
    m_imageWidth = imageWidth;
    m_imageHeight = imageHeight;
    m_scale = scale;
    m_offset = offset;

    // 清除之前的绘制项
    removeAllItems();

    // 计算图像中心点（场景坐标）
    QPointF centerScene = imageToSceneCoordinates(QPointF(imageWidth / 2.0, imageHeight / 2.0));
    
    // 计算矩形位置（使矩形位于图像中心）
    QRectF rectScene;
    rectScene.setWidth(defaultWidth * scale);
    rectScene.setHeight(defaultHeight * scale);
    rectScene.moveCenter(centerScene);

    // 创建矩形项
    m_rectItem = createRectItem(rectScene);
    addDrawingItem(m_rectItem);

    // 初始信号触发
    onRectPositionChanged();
}

void RectangleRegionDrawer::clearAll()
{
    removeAllItems();
    m_rectItem = nullptr;
    m_drawingItems.clear();
}

QVariantMap RectangleRegionDrawer::getMeasurementResult() const
{
    if (!m_rectItem) {
        qWarning() << "矩形项未设置，无法获取测量结果";
        return QVariantMap();
    }

    QVariantMap result;
    QRectF rectScene = m_rectItem->rect();
    
    // 转换为图像像素坐标
    QPointF topLeftImage = sceneToImageCoordinates(rectScene.topLeft());
    QPointF bottomRightImage = sceneToImageCoordinates(rectScene.bottomRight());
    
    QRectF rectImage(topLeftImage, bottomRightImage);

    // 存储测量结果
    result["x"] = rectImage.x();
    result["y"] = rectImage.y();
    result["width"] = rectImage.width();
    result["height"] = rectImage.height();


    return result;
}

MeasurementMode RectangleRegionDrawer::getMeasurementMode() const
{
    return MeasurementMode::RectangleRegion;
}

void RectangleRegionDrawer::restoreFromResult(const QVariantMap &result, double scale, const QPointF &offset)
{
    if (!m_scene) {
        qWarning() << "场景未设置，无法恢复绘制";
        return;
    }

    // 更新缩放和偏移信息
    m_scale = scale;
    m_offset = offset;



    // 清除之前的绘制项
    removeAllItems();

    // 从结果中提取矩形信息
    if (result.contains("x") && result.contains("y") && 
        result.contains("width") && result.contains("height")) {
        
        // 原始图像坐标
        qreal x = result["x"].toReal();
        qreal y = result["y"].toReal();
        qreal width = result["width"].toReal();
        qreal height = result["height"].toReal();

        // 转换为场景坐标
        QPointF topLeftScene = imageToSceneCoordinates(QPointF(x, y));
        QPointF bottomRightScene = imageToSceneCoordinates(QPointF(x + width, y + height));
        
        QRectF rectScene(topLeftScene, bottomRightScene);
        m_rectItem = createRectItem(rectScene);
        addDrawingItem(m_rectItem);
        
        // 触发位置变化信号
        onRectPositionChanged();
    }
}

void RectangleRegionDrawer::setParameters(const QVariantMap &params)
{
    // 从参数中提取样式设置
    if (params.contains("line_color")) {
        m_lineColor = params.value("line_color").value<QColor>();
    }
    if (params.contains("line_width")) {
        m_lineWidth = params.value("line_width").toInt();
    }
    if (params.contains("fill_color")) {
        m_fillColor = params.value("fill_color").value<QColor>();
    }
    if (params.contains("fill_opacity")) {
        m_fillOpacity = params.value("fill_opacity").toDouble();
    }

    // 更新样式
    initializeStyles();

    // 更新现有矩形项的样式
    if (m_rectItem) {
        m_rectItem->setPen(m_rectPen);
        m_rectItem->setBrush(m_rectBrush);
    }
}

void RectangleRegionDrawer::updateTransformInfo(double scale, const QPointF &offset)
{
    if (m_scale == scale && m_offset == offset) {
        return; // 没有变化，不需要更新
    }
    
    // 保存当前图像坐标（基于旧的缩放和偏移）
    QPointF topLeftImage, bottomRightImage;
    bool hasRect = m_rectItem != nullptr;
    if (hasRect) {
        QRectF currentRect = m_rectItem->rect();
        topLeftImage = sceneToImageCoordinates(currentRect.topLeft());
        bottomRightImage = sceneToImageCoordinates(currentRect.bottomRight());
    }
    
    // 更新缩放和偏移
    m_scale = scale;
    m_offset = offset;
    
    // 使用新的缩放和偏移将图像坐标转换回场景坐标
    if (hasRect) {
        QPointF newTopLeftScene = imageToSceneCoordinates(topLeftImage);
        QPointF newBottomRightScene = imageToSceneCoordinates(bottomRightImage);
        
        // 更新矩形位置
        m_rectItem->setRect(QRectF(newTopLeftScene, newBottomRightScene));
        onRectPositionChanged();
    }
}

void RectangleRegionDrawer::setScale(double scale)
{
    // 调用updateTransformInfo方法，保持偏移不变，只更新缩放
    updateTransformInfo(scale, m_offset);
}

void RectangleRegionDrawer::addDrawingItem(QGraphicsItem *item)
{
    if (m_scene && item) {
        // 设置zValue大于图像项的zValue(0)，确保绘制项显示在图像上方
        item->setZValue(1);
        m_scene->addItem(item);
        m_drawingItems.append(item);
    }
}

void RectangleRegionDrawer::removeAllItems()
{
    if (m_scene) {
        for (QGraphicsItem *item : m_drawingItems) {
            m_scene->removeItem(item);
            delete item;
        }
    }
    m_drawingItems.clear();
}

DraggableRectItem *RectangleRegionDrawer::createRectItem(const QRectF &rect)
{
    DraggableRectItem *rectItem = new DraggableRectItem(rect);
    rectItem->setPen(m_rectPen);
    rectItem->setBrush(m_rectBrush);
    rectItem->setResizable(true); // 启用调整大小功能
    
    // 连接位置变化信号
    connect(rectItem, &DraggableRectItem::positionChanged, this, &RectangleRegionDrawer::onRectPositionChanged);
    connect(rectItem, &DraggableRectItem::sizeChanged, this, &RectangleRegionDrawer::onRectPositionChanged);
    
    return rectItem;
}

void RectangleRegionDrawer::initializeStyles()
{
    // 设置默认样式
    m_lineWidth = 2;
    m_lineColor = Qt::blue;
    m_fillColor = Qt::blue;
    m_fillOpacity = 0.3;

    // 初始化画笔和画刷
    m_rectPen = QPen(m_lineColor, m_lineWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
    
    // 创建半透明的填充色
    QColor fillColor = m_fillColor;
    fillColor.setAlphaF(m_fillOpacity);
    m_rectBrush = QBrush(fillColor);
}

QPointF RectangleRegionDrawer::sceneToImageCoordinates(const QPointF &scenePos) const
{
    // 场景坐标 -> 图像像素坐标
    QPointF imagePos;
    imagePos.setX((scenePos.x() - m_offset.x()) / m_scale);
    imagePos.setY((scenePos.y() - m_offset.y()) / m_scale);
    return imagePos;
}

QPointF RectangleRegionDrawer::imageToSceneCoordinates(const QPointF &imagePos) const
{
    // 图像像素坐标 -> 场景坐标
    QPointF scenePos;
    scenePos.setX(imagePos.x() * m_scale + m_offset.x());
    scenePos.setY(imagePos.y() * m_scale + m_offset.y());
    return scenePos;
}

void RectangleRegionDrawer::onRectPositionChanged()
{
    if (!m_rectItem) {
        return;
    }
    
    // 获取场景坐标中的矩形
    QRectF rectScene = m_rectItem->rect();
    qDebug()<<rectScene;
    // 转换为图像像素坐标
    QPointF topLeftImage = sceneToImageCoordinates(m_rectItem->pos());
    QPointF bottomRightImage = sceneToImageCoordinates(rectScene.bottomRight());
    
    QRectF rectImage(topLeftImage, bottomRightImage);
    
    // 发送信号，上报图像像素坐标
    emit rectangleChanged(rectImage);
}
